package mulMan.gui.controller;

import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;

import mulMan.domain.Playlist;
import mulMan.gui.view.AddPlaylistView;
import mulMan.gui.view.ModifyPlaylistView;
import mulMan.gui.view.PlaylistFullView;
import mulMan.gui.view.PlaylistMenuView;

public class PlaylistController extends Observable{
	
	private Playlist playlist;
	private Container view;
	private AudioFilesController audioFilesController;
	
	public void setAudioFilesController(AudioFilesController audioFilesController) {
		this.audioFilesController = audioFilesController;
	}
	
	
	public PlaylistController(Playlist playlist, Container view) {
		this.playlist = playlist;
		this.view = view;
		
		if (view instanceof AddPlaylistView) {
			((AddPlaylistView)view).addAddPlaylistListener(new AddPlaylistListener());
		} else if (view instanceof ModifyPlaylistView) {
			((ModifyPlaylistView)view).addModifyPlaylistListener(new ModifyPlaylistListener());
		} else if (view instanceof PlaylistMenuView) {
			((PlaylistMenuView) view).addAddAudioFileToPlaylistListener(new AddAddAudioFileToPlaylistListener());
		}
	}
	
	
	//ACTION LISTENERS
	
	class AddPlaylistListener implements ActionListener {
	    public void actionPerformed(ActionEvent e) {
	    	if (checkFields()) {
		    	try {
					playlist.savePlaylist();
				} catch (Exception e1) {
					e1.printStackTrace();
				}
		    	((AddPlaylistView)view).getButtonAdd().setEnabled(false);
		    	((AddPlaylistView)view).dispose();
	    	}
	    }
	}
	
	class ModifyPlaylistListener implements ActionListener {
	    public void actionPerformed(ActionEvent e) {
	    	if (checkFields()) {
		    	try {
					playlist.updatePlaylist();
				} catch (Exception e1) {
					e1.printStackTrace();
				}
		    	((ModifyPlaylistView)view).getButtonModify().setEnabled(false);
		    	((ModifyPlaylistView)view).dispose();
		    }
	    }
	}
	
	public boolean checkFields() {
		((PlaylistFullView) view).resetErrors();
		boolean valid = false;
		
		if (((PlaylistFullView) view).getNameTextField().getText().equals("")) {
			((PlaylistFullView) view).getErrorLabel().setText("The name of the playlist must be given");
			((PlaylistFullView) view).getNameLabel().setForeground(Color.RED);
		} else {
			playlist.setName(((PlaylistFullView) view).getNameTextField().getText());
			valid= true;
		}
		return valid;
	}
	
	class AddAddAudioFileToPlaylistListener implements ActionListener {

		public void actionPerformed(ActionEvent arg0) {
			playlist.addAudioFileToPlaylist(audioFilesController.getSelectedAudioFile());
		}
		
	}
}
